<?php
/**
 * 
 * 
 * $Rev:$
 * $Author:$
 * $Date:$
 * $Id:$
 * $URL:$
 * @author: Adrian Liechti <info@jahweh.ch>
 * @copyright: 2010 Adrian Liechti, GPL3 and CC3 BY-SA
 */

class moduleFunctions {
	
	public function __construct () {
	
	}
	
	public static function registerSave () {
		global $db, $pluginLoader;
		
		$t = new timeStamp('moduleRegisterSave', false, false);
		
		$t->start('select');
		$modules_q = $db->query("SELECT class_name, name, module_id, path, plugin_name, useable, class_name FROM modules;");
		if ($modules_q !== false) {
			$dbModules = $modules_q->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_UNIQUE|PDO::FETCH_ASSOC);
		} else {
			return false;
		}
		$t->end();
		
		$rgModules =& $pluginLoader->register->module;
		
		$t->start('refresh');
		foreach ($rgModules as $rgM) {
			if (isset($dbModules[(string)$rgM['class']])) {
				$dbM =& $dbModules[(string)$rgM['class']];
				if ((string)$rgM['name'] === $dbM['name']
					and (string)$rgM['path'] === $dbM['path']
					and (string)$rgM['class'] === $dbM['class_name']
					and (string)$rgM['pluginName'] === $dbM['plugin_name']
					and (string)$rgM['useable'] === $dbM['useable']) continue;
				$db->exec("
					UPDATE modules SET
						name		= ".$db->quote($rgM['name']).",
						path		= ".$db->quote($rgM['path']).",
						class_name	= ".$db->quote($rgM['class']).",
						plugin_name	= ".$db->quote($rgM['pluginName']).",
						useable		= ".$db->quote($rgM['useable'])."
					WHERE
						module_id	= ".$db->quote($dbModules[(string)$rgM['class']]['module_id'])."
					LIMIT 1");
			} else {
				$db->exec("
					INSERT INTO modules (
						name, path, class_name, plugin_name, useable
					) VALUES (
						".$db->quote($rgM['name']).",
						".$db->quote($rgM['path']).",
						".$db->quote($rgM['class']).",
						".$db->quote($rgM['pluginName']).",
						".$db->quote($rgM['useable'])."
					)");
			}
		}
		$t->end();
		
		$t->start('remove');
		foreach ($dbModules as $dbM) {
			$m = $pluginLoader->register->xpath('child::module[attribute::class="'.$dbM['class_name'].'"]');
			if (isset($m) === false) {
				/**
				 * TODO Simple Remove for Modules
				 */
				$db->exec("
					DELETE FROM
						modules
					WHERE
						module_id = ".$db->quote($dbM['module_id'])."
					LIMIT 1");
			}
		}
		$t->end();
		
		return true;
	}
	
}
?>